<template>
  <div class="agent-bg">
    <div class="agent-header">
      <span class="back-btn" @click="goHome">← 返回</span>
      <span class="title">AI超级智能体</span>
    </div>
    <div class="agent-chat-card">
      <div class="chat-history" ref="historyRef">
        <template v-for="(msg, msgIdx) in messages">
          <template v-if="splitAiSteps(msg)">
            <div
              v-for="(seg, idx) in splitAiSteps(msg)"
              :key="msgIdx + '-' + idx"
              class="chat-message ai"
            >
              <div class="avatar">
                <span class="emoji">🤖</span>
              </div>
              <div class="chat-bubble">　　{{ seg }}</div>
            </div>
          </template>
          <template v-else>
            <div :class="['chat-message', msg.role]" :key="msgIdx" v-if="msg.content && msg.content.trim()">
              <div class="avatar">
                <span v-if="msg.role==='ai'" class="emoji">🤖</span>
                <span v-else class="emoji user">我</span>
              </div>
              <div class="chat-bubble">
                <span v-for="(line, idx) in msg.content.split(/\n+/)" :key="idx">
                  {{ msg.role === 'user' ? line : '　　' + line }}<br v-if="idx !== msg.content.split(/\n+/).length - 1" />
                </span>
              </div>
            </div>
          </template>
        </template>
        <div v-if="thinking" class="chat-message ai">
          <div class="avatar">
            <span class="emoji">🤖</span>
          </div>
          <div class="chat-bubble">思考中...</div>
        </div>
      </div>
      <div class="chat-input-bar">
        <input v-model="input" @keyup.enter="sendMessage" placeholder="请输入消息..." />
        <button @click="sendMessage">发送</button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, nextTick, computed } from 'vue';
import { useRouter } from 'vue-router';
import axios from 'axios';
import { getMessageList, doChatWithManusSse } from '../api';
const router = useRouter();
const goHome = () => router.push('/');
const input = ref('');
const SESSION_KEY = 'super_agent_chat_id';
let chatId = sessionStorage.getItem(SESSION_KEY);
if (!chatId) {
  chatId = Math.random().toString(36).slice(2) + Date.now();
  sessionStorage.setItem(SESSION_KEY, chatId);
}
const messages = ref([]);
const historyRef = ref(null);
let sse = null;
const thinking = ref(false);

const splitAiSteps = (msg) => {
  if (msg.role === 'ai' && msg.content.match(/^Step \d+: /m)) {
    return msg.content.split(/(?=Step \d+: )/).filter(seg => seg.trim());
  }
  return null;
};

function scrollToBottom() {
  nextTick(() => {
    if (historyRef.value) {
      historyRef.value.scrollTop = historyRef.value.scrollHeight;
    }
  });
}
function sendMessage() {
  const text = input.value.trim();
  if (!text) return;
  messages.value.push({ id: Date.now() + '-user', role: 'user', content: text });
  input.value = '';
  scrollToBottom();
  if (sse) sse.close();
  thinking.value = true;
  sse = doChatWithManusSse(text);
  let aiMsg = { id: Date.now() + '-ai', role: 'ai', content: '' };
  messages.value.push(aiMsg);
  sse.onmessage = (e) => {
    aiMsg.content += e.data;
    messages.value = [...messages.value];
    thinking.value = false;
    scrollToBottom();
  };
  sse.onerror = () => {
    sse.close();
    thinking.value = false;
  };
}
async function fetchHistory() {
  try {
    const res = await getMessageList(chatId);
    const data = res.data;
    const arr = [];
    if (data.user) {
      data.user.forEach((msg) => {
        arr.push({ role: "user", content: msg });
      });
    }
    if (data.assistant) {
      data.assistant.forEach((msg) => {
        arr.push({ role: "ai", content: msg });
      });
    }
    messages.value = arr;
    scrollToBottom();
  } catch (e) {}
}
onMounted(() => {
  fetchHistory();
  scrollToBottom();
});
</script>

<style scoped>
.agent-bg {
  min-height: 100vh;
  background: #f6f8fc;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.agent-header {
  width: 100vw;
  max-width: 100%;
  background: linear-gradient(90deg, #4de2ff 0%, #1a6fa6 100%);
  color: #fff;
  font-size: 1.2rem;
  font-weight: bold;
  padding: 0.7rem 3vw;
  display: flex;
  align-items: center;
  position: sticky;
  top: 0;
  z-index: 10;
  border-radius: 0 0 18px 18px;
  box-shadow: 0 2px 12px #4de2ff33;
}
.back-btn {
  cursor: pointer;
  margin-right: 1.5rem;
  color: #fff;
  font-size: 1.1rem;
}
.title {
  flex: 1;
  text-align: center;
  font-size: 1.3rem;
  font-weight: bold;
  letter-spacing: 1px;
}
.agent-chat-card {
  background: #fff;
  border-radius: 18px;
  box-shadow: 0 2px 12px #4de2ff22;
  margin: 2rem 0 1rem 0;
  width: 700px;
  max-width: 96vw;
  min-width: 320px;
  display: flex;
  flex-direction: column;
  min-height: 60vh;
  position: relative;
  transition: box-shadow 0.2s;
}
.chat-history {
  flex: 1;
  overflow-y: auto;
  padding: 1.5rem 1.2rem 1rem 1.2rem;
  display: flex;
  flex-direction: column;
  gap: 1.5rem;
  min-height: 300px;
}
.chat-message {
  display: flex;
  align-items: flex-end;
  margin-bottom: 0.2rem;
}
.chat-message.user {
  flex-direction: row-reverse;
}
.avatar {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 0 0.3rem;
}
.emoji {
  font-size: 1.3rem;
  background: #e6f7ff;
  border-radius: 50%;
  padding: 0.15rem 0.25rem;
}
.emoji.user {
  background: #1890ff;
  color: #fff;
  font-size: 1rem;
  padding: 0.15rem 0.6rem;
}
.chat-bubble {
  max-width: 80vw;
  min-width: 36px;
  padding: 0.6rem 1rem;
  border-radius: 20px;
  font-size: 0.98rem;
  word-break: break-all;
  box-shadow: 0 1px 4px #eee2;
  line-height: 1.6;
}
.chat-message.user .chat-bubble {
  background: #1890ff;
  color: #fff;
  border-bottom-right-radius: 8px;
}
.chat-message.ai .chat-bubble {
  background: #f5f5f5;
  color: #444;
  border-bottom-left-radius: 8px;
}
.chat-input-bar {
  display: flex;
  padding: 0.7rem 1rem;
  border-top: 1px solid #f0f0f0;
  background: #fff;
  border-radius: 0 0 18px 18px;
  position: sticky;
  bottom: 0;
  z-index: 2;
}
.chat-input-bar input {
  flex: 1;
  padding: 0.6rem;
  border: 1px solid #ccc;
  border-radius: 4px;
  font-size: 1rem;
}
.chat-input-bar button {
  margin-left: 0.7rem;
  padding: 0.6rem 1.2rem;
  font-size: 1rem;
  border: none;
  border-radius: 4px;
  background: #1a6fa6;
  color: #fff;
  cursor: pointer;
  font-weight: bold;
  box-shadow: 0 1px 4px #4de2ff33;
}
.agent-footer {
  width: 100vw;
  min-width: 320px;
  max-width: 100vw;
  text-align: center;
  color: #888;
  font-size: 1rem;
  padding: 1.2rem 0 0.7rem 0;
  display: flex;
  justify-content: center;
  gap: 2rem;
  margin: 0 auto;
}
.footer-link {
  margin-left: 2rem;
  color: #888;
  cursor: pointer;
  font-size: 1rem;
}
.agent-footer, .footer-link, .agent-chat-card, .chat-bubble {
  word-break: break-all;
}
@media (max-width: 800px) {
  .agent-header {
    border-radius: 0;
    padding: 0.7rem 4vw;
    font-size: 1.05rem;
  }
  .title {
    font-size: 1.08rem;
  }
  .agent-chat-card {
    width: 100vw;
    max-width: 100vw;
    min-width: 0;
    border-radius: 0;
    margin: 0;
    min-height: 60vh;
    box-shadow: 0 1px 4px #4de2ff22;
  }
  .chat-bubble {
    font-size: 0.92rem;
  }
  .agent-footer {
    font-size: 0.9rem;
    padding: 0.7rem 0 0.5rem 0;
    gap: 1rem;
    min-width: 0;
  }
  .footer-link {
    font-size: 0.9rem;
  }
}
</style> 